import json
import random
import time

import requests
requests.packages.urllib3.disable_warnings()

# 获取签到状态
def getSignStatus():
    url = 'https://wx.17u.cn/wxmpsign/sign/getSignInfo'
    data = {}
    data = baseRequest(url, headers, data)
    print(data)
    if data['code'] == 200:
        data = data['data']
        todaySigned = data['todaySigned']
        signStatus = '已签到' if todaySigned else '未签到'
        print(f'签到状态：{signStatus}')
        if todaySigned == 0:
            print('开始签到')
            saveSignInfo()
    else:
        print(data)

# 签到
def saveSignInfo():
    url = 'https://wx.17u.cn/wxmpsign/sign/saveSignInfo'
    data = {}
    data = baseRequest(url, headers, data)
    print(data)
    if data['code'] == 200:
        data = data['signMileage']
        signMileage = data['signMileage']
        extraMileage = data['extraMileage']
        print(f'签到完成，+{signMileage}里程，额外奖励+{extraMileage}里程')
    else:
        print('签到失败', data['msg'])

# 获取任务列表
def getTaskList():
    url = 'https://wx.17u.cn/wcsign/SignTask/GetTaskList'
    data = {
        "unionId": unionId,
        "openId": taskOpenId
    }
    print(data)
    headers['sectoken'] = requestToken
    data = baseRequest(url, headers, data)
    taskStatusArray = {
        0: '待完成',
        1: '待领奖',
        2: '已完成'
    }
    if data['rspCode'] == 0:
        taskList = data['data']
        for task in taskList:
            activityId = task['activityId']
            taskId = task['taskId']
            taskTitle = task['taskName']
            taskAward = task['awardDesc']
            taskType = task['taskType']
            # completeStatus = 2 是已完成 0 是待完成 1 是待领奖
            taskStatus = task['completeStatus']
            print(
                f'任务ID：{taskId}，任务标题：【{taskTitle}】，任务奖励：【{taskAward}】，任务状态：{taskStatusArray[taskStatus]}')
            if taskStatus == 1:
                receiveTask(taskId)
            elif taskStatus == 0:
                randTime = random.randint(2, 4)
                print('正在完成任务ID：', taskId, '等待时间', randTime)
                time.sleep(randTime)
                commitTask(taskId, activityId, taskType)
                randTime = random.randint(1, 2)
                print('正在领取任务ID：', taskId, '等待时间', randTime)
                time.sleep(randTime)
                receiveTask(taskId)
            elif taskStatus == 2:
                print('任务已完成', taskId)

    else:
        print('获取失败', data)


# 领取奖励
def receiveTask(taskId):
    url = 'https://wx.17u.cn/wcsign/SignTask/ReceiveTaskAward'
    data = {
        "unionId": unionId,
        "openId": taskOpenId,
        "taskId": taskId
    }
    data = baseRequest(url, headers, data)
    print('领取结果', data)

# 领取加桌面奖励
def desktopReward():
    url = 'https://wx.17u.cn/wxmpsign/sign/retrieveDesktopReward'
    data = {
        "unionId": unionId,
        "openId": taskOpenId,
        "userIcon": "https://file.40017.cn/img140017cnproduct/touch/pushcode/qiandao/2020a/icon_defaultheader.png",
        "nickName": "匿名好友",
        "isFromWindow": True,
        "version": 63,
        "encryptedData": "93baff6c2920837e29cd15e4151b29f44688dcdf581d6c0c8015786cc12ed42c4a4e9eb1e7916237856917b56d869f05662919078593f9b336474294e13649c8284f929546424dfcd5a4f26be086fca41bd7588be99061955ad6aca75456a9cd4d4f2013d343f8f52db8cd92a1f5ae832a71ff31d84801b9506fe9d73105324d978412d0d22f02cb768bb42258e3621f70c054ef38b519b4136d69d2c530103c4de5e9ab5393a52ba931dc7cb631e9d494fc02c0793eae1a40e4175e5c561bba454222e84d67bee010ef84ad3d456b6ab5f7ff06e1df733ca6ff78e26f38cf6a0cbe57e0a02b83274ee3acf4f8968b09"
    }
    data = baseRequest(url, headers, data)
    print('桌面奖励领取结果', data)

# 提交任务
def commitTask(taskId, activityId, taskType):
    url = 'https://wx.17u.cn/wcsign/SignTask/SaveTaskAction'
    data = {
        "unionId": unionId,
        "openId": taskOpenId,
        "taskId": taskId,
        "activityId": activityId,
        "taskType": taskType
    }
    data = baseRequest(url, headers, data)
    print('领取结果', data)


# 查看昨天收益
def getYesterdayProfit():
    url = 'https://wx.17u.cn/wxmpsign/home/bubble'
    data = {
        "version": 1
    }
    data = baseRequest(url, headers, data)
    if data['code'] == 200:
        data = data['data']
        bubbles = data['bubbles']
        for bubble in bubbles:
            if bubble['title'] == '昨日收益' or bubble['title'] == '历史收益':
                print(bubble['title'], '为', str(bubble['coin']) + '里程')
                incomeId = bubble['incomeId']
                bubleType = bubble['type']
                receviceInCome(bubble['title'], incomeId, bubleType)
            if bubble['title'] == '桌面奖励':
                desktopReward()

# 获取省钱中心签到
def getShengqian():
    url = 'https://wx.17u.cn/car-inter-h5/quickcar/activity/saveMoneyCenterSignIn'
    data = {
        "platform": "xcx",
        "memberId": "",
        "unionId": unionId,
        "unionid": unionId,
        "openId": taskOpenId,
        "openid": taskOpenId,
        "headImg": '',
        "userName": ''
    }
    data = baseRequest(url, headers, data)
    body = data['response']['body']
    if body['status'] == 200:
        # data = body['body']
        print(body)


# 领取昨日收益
def receviceInCome(title, incomeId, type):
    url = 'https://wx.17u.cn/wxmpsign/home/receiveIncome'
    data = {
        "incomeId": incomeId,
        "type": type
    }
    data = baseRequest(url, headers, data)
    print('领取'+title+'结果', data)


# 商城抽奖
def shopLottery():
    url = 'https://wx.17u.cn/wcrewardshopapiv2/roulette/lottery'
    accessToken = '73_NYqP9v2j2v1qo5ffij9elxCIxPshV9M0u6x_Srn1O7t1MVEZoXg2jjzMzNxO-ellap0Wfup1WPKTT-fwzSKndWdaf0USV2B_57YQeMXJaYw'
    data = {
        "openId": lotteryOpenId,
        "unionId": unionId,
        "access_token": accessToken,
        "secToken": accessToken,
        "osType": 1,
        "onceFlag": True,
        "hostFakeUid": "",
        "playId": "IXuH79YDGkYNShOZEHy69g==",
        "nickName": "此用户未填昵称",
        "taskNo": ""
    }
    headers['Referer'] = 'Referer: https://wx.17u.cn/memberlc/mileageshop/luckyWheel?refid=1486690823&rum_webTime=1697167615601&rum_webType=2'
    headers['openId'] = lotteryOpenId
    headers['userKey'] = unionId
    headers['Host'] = 'wx.17u.cn'
    headers['platformSub'] = 'WX_MP'
    headers['platform'] = 'WX_MP'
    headers['Origin'] = 'https://wx.17u.cn'
    headers['accountSystem'] = '1'
    headers['osType'] = '1'
    headers['UserToken'] = requestToken

    data = baseRequest(url, headers, data)
    if data['hasSuccess']:
        print('抽奖结果：', data['data']['prizeName'])
    else:
        print('抽奖结果：', data['resultInfo'])

# 发起请求
def baseRequest(url , headers , data):
    try:
        result = requests.post(url, headers=headers, data=json.dumps(data), verify=False)
        content = result.content.decode('utf8')
        data = json.loads(content)
        print(data)
        return data
    except Exception as e:
        print(e)

if __name__ == '__main__':
    loginResp = {
        "openId": "o498X0S2rm4K8tn3HQwItbtJPJdw",
        "unionId": "ohmdTtz4uZ8UgIEYMhJCrzFgnlYs",
        "encryOpenId": "7a932c7ca08344cbdf434f6307778119",
        "aesOpenId": "HvY9DcAJmeXzvnZX4iMrpmrWAn6wkKDsKWC72BJWknA=",
        "aesUnionId": "WZBPbJ01N4GWmvSAfLTDJYBo1z+y2SJMLZKr5MzNcIk=",
        "memberId": "DxElSxQsauvq/agVmeNXxg==",
        "sectoken": "ZfOeS2YX9IStsHx-3-C4u5Wbys47UFTJNPMc9VYHhxZzJzU4a2IsIMRKaAwJ-mTvOUnqTEndSBhxeCaOuXguCM7AeQCeUj0rEuojM0xOxuXQDR8ggKygJCQLLw5agVr1ByI-F-20T0VQK2mr_7DNwSADgYgWRP9iAVg5PAiM-ous2rkqcxsPl7Qa2A6xwaU5kFb62RAfS0APtByllgxWvg**4641",
        "expts": 1703034841,
        "tcRegister": 0
    }
    taskOpenId = loginResp['openId']
    requestToken = loginResp['sectoken']
    headers = {
        'Host': 'wx.17u.cn',
        'TC-MALL-PLATFORM-SUB': 'ALIPAY',
        'TC-MALL-PLATFORM-CODE': 'ALIPAY',
        'TC-MALL-DEPT-CODE': 'iH3PGf9ZucSMMEYi4keylA==',
        'TC-MALL-CLIENT': 'API_CLIENT',
        'TC-MALL-OPEN-ID': '031T70yTBjgJA2ShgyA4xQYr6cRy7EDvXSGVdp2GemB2cc5',
        'TC-MALL-OS-TYPE': 'IOS',
        'content-type': 'application/json',
        'TCReferer': 'page%2FAC%2Fsign%2Fmsindex%2Fmsindex',
        'TC-MALL-USER-TOKEN': '87DySn4Me6M2N835L7CvfYGR2ktgGqUnaeAkd6fIZAFi1rwix5ZekZ8ZeePsfp3uhrYTxRElyhiS__1ESabGydEw**',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/20F770750d Ariver/1.1.0 AliApp(AP/10.5.56.6000) Nebula WK RVKType(1) AlipayDefined(nt:WIFI,ws:375|748|3.0) AlipayClient/10.5.56.6000 Language/zh-Hans Region/CN MiniProgram APXWebView NebulaX/1.0.0',
        'Referer': 'https://wx.17u.cn/mileagemall/activity/mallVue3/home?showTabbar=1&refid=2000075342'
    }

    lotteryOpenId = 'oOCyauDUsaos99k34SXnU06yoaws'
    unionId = loginResp['unionId']
    # 先签到，再来完成任务
    print('-----------------开始签到流程-----------------')
    getSignStatus()
    # # 完成任务
    # print('-----------------开始任务流程-----------------')
    # getTaskList()
    # # 领取昨日收益
    # print('-----------------开始昨日收益领取流程-----------------')
    # getYesterdayProfit()
    # # 领取省钱中心里程
    # print('-----------------开始省钱中心流程-----------------')
    # getShengqian()
    # # 商城抽奖
    # print('-----------------开始抽奖流程-----------------')
    # shopLottery()